package com.mg.plugin.agrometeorology.model;

import com.mg.model.Model;
import com.mg.model.Param;
import com.mg.model.Port;
import com.mg.plugin.agrometeorology.common.DataFormatter;
import com.mg.plugin.agrometeorology.common.DateCalculator;
import com.mg.plugin.agrometeorology.common.OstriniaNubilalisCalculator;
import com.mg.plugin.agrometeorology.common.StationDataType;
import com.mg.plugin.agrometeorology.entity.StationData;
import com.mg.pluginexample2.ModuleBase;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 玉米螟
 */
public class OstriniaNubilalisModel extends ModuleBase {

    public OstriniaNubilalisModel(int nID) {
        super(nID);
        m_alInputPort.add(new Port(this, Port.Type.Unknown));
        m_alInputPort.add(new Port(this, Port.Type.Unknown));
        m_alOutputPort.add(new Port(this, Port.Type.Unknown));
    }

    public String GetGroupName() {
        return "灾害制作";
    }

    public String GetName() {
        return "玉米螟";
    }

    public String GetDescription() {
        return "吉林灾害制作";
    }

    public boolean OnAttach(Port portFrom, Port portTo) {
        try {
            int i = FindPort(portFrom, false);
            if (i != -1) {
                return true;
            }
            i = FindPort(portTo, true);
            if (i == -1) {
                return false;
            }

            ArrayList<Param> alParam = new ArrayList<Param>();
            portFrom.GetModule().GetOutputParam(portFrom, alParam);

            if (alParam.size() != 1) {
                return false;
            }

            if (alParam.get(0).m_objValue != null && !(alParam.get(0).m_objValue instanceof ArrayList)) {
                m_model.OutputLog(Model.LogLevel.Error, "No ArrayList");
                return false;
            }
            if (i == 0) {
                m_model.OutputLog(Model.LogLevel.Info, "m_inputForecastList" + alParam.get(0).m_objValue.getClass());
                m_inputForecastList = (List<String>) alParam.get(0).m_objValue;
            }
            if (i == 1) {
                m_model.OutputLog(Model.LogLevel.Info, "m_inputRealityList" + alParam.get(0).m_objValue.getClass());
                m_inputRealityList = (List<String>) alParam.get(0).m_objValue;
            }

            portTo.SetType(portFrom.GetType());
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        }
        return true;
    }

    public boolean OnDetach(Port portFrom, Port portTo) {
        if (!super.OnDetach(portFrom, portTo))
            return false;
        try {
            int i = FindPort(portTo, true);
            if (i == -1)
                return true;
            return true;
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        }
    }

    //用于 参数->XML 等
    public int GetParam(ArrayList<Param> alParam) {
        try {
            super.GetParam(alParam);
            String selectData = "WINTERING|RECOVERY|PHLEGM|FEATHERING|INCUBATION|LARVAL|FGP|SGP";
            alParam.add(new Param("BeginDate", m_strBeginDate, "计算时期", "计算时期：依次为越冬期、复苏期、化蛹期、羽化期、孵化期、幼虫期、一代全发育期、二代全发育期", "时期", Param.EditType.Select, selectData));
            alParam.add(new Param("StationId", m_strStationId, "站点ID对应字段", "StationId", "参数匹配", Param.EditType.Default));
            alParam.add(new Param("Lat", m_strLat, "站点纬度", "Lat", "参数匹配", Param.EditType.Default));
            alParam.add(new Param("Lon", m_strLon, "站点经度", "Lon", "参数匹配", Param.EditType.Default));
            alParam.add(new Param("Date", m_strDate, "时间对应字段", "Date", "参数匹配", Param.EditType.Default));
            alParam.add(new Param("Temperature", m_strTemp, "温度对应字段", "Temperature", "参数匹配", Param.EditType.Default));
            alParam.add(new Param("MaxTemperature", m_strMaxTemp, "最高温度对应字段", "MinTemperature", "参数匹配", Param.EditType.Default));
            alParam.add(new Param("Precipitation", m_strRain, "降水对应字段", "Precipitation", "参数匹配", Param.EditType.Default));
            alParam.add(new Param("Humidity", m_strHumidity, "湿度对应字段", "Humidity", "参数匹配", Param.EditType.Default));

        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return alParam.size();
    }

    public boolean OnParamChanged(ArrayList<Param> alParam, int nIndex, Object objValue) {
        return super.OnParamChanged(alParam, nIndex, objValue);
    }

    //用于 XML->参数 等
    public int SetParam(final ArrayList<Param> alParam) {
        int i = super.SetParam(alParam);
        try {
            m_strBeginDate = (String) alParam.get(i++).m_objValue;
            m_strStationId = (String) alParam.get(i++).m_objValue;
            m_strLat = (String) alParam.get(i++).m_objValue;
            m_strLon = (String) alParam.get(i++).m_objValue;
            m_strDate = (String) alParam.get(i++).m_objValue;
            m_strTemp = (String) alParam.get(i++).m_objValue;
            m_strMaxTemp = (String) alParam.get(i++).m_objValue;
            m_strRain = (String) alParam.get(i++).m_objValue;
            m_strHumidity = (String) alParam.get(i++).m_objValue;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return i;
    }

    public int GetOutputParam(Port port, ArrayList<Param> alParam) {
        int i = FindPort(port, false);
        if (i == -1) {
            System.out.println("Post Is Null");
            return 0;
        }

        alParam.add(new Param("ResultString", m_listCSV));
        return alParam.size();
    }

    @SuppressWarnings("static-access")
    public boolean Execute() {

        m_listCSV.clear();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String head = "StationNum,Data,Time";
        String type = "String,Double,String";
        m_listCSV.add(head);
        m_listCSV.add(type);

        Map<String, List<StationData>> stationDataList = new HashMap<String, List<StationData>>();

        Map<String, String> headerIndex = new HashMap<String, String>();
        headerIndex.put("StationId", m_strStationId);
        headerIndex.put("Lat", m_strLat);
        headerIndex.put("Lon", m_strLon);
        headerIndex.put("Date", m_strDate);
        headerIndex.put("Humidity", m_strHumidity);
        headerIndex.put("Temp", m_strTemp);
        headerIndex.put("MaxTemp", m_strMaxTemp);
        headerIndex.put("Rain", m_strRain);

        try {
            DataFormatter.formatStationData(m_inputRealityList, m_inputForecastList, headerIndex, StationDataType.OSTRINIA, stationDataList);
        } catch (ParseException e) {
            return false;
        }

        try {
            for (String stationId : stationDataList.keySet()) {
                float g = OstriniaNubilalisCalculator.calcDisasterLevel(stationDataList.get(stationId), m_strBeginDate, m_model);
                if (!Float.isNaN(g) && !Float.isInfinite(g)) {
                    m_listCSV.add(stationId + "," + g + "," + sdf.format(new Date()));
                }

            }
        } catch (ParseException e) {
            m_model.OutputLog(Model.LogLevel.Error, "ParseException!");
            e.printStackTrace();
            return false;
        }
        OnParamChanged();
        return true;
    }

    private int findDataIndex(String realHeader, String strRain) {

        String[] data = realHeader.split(",");
        for (int i = 0; i < data.length; i++) {
            if (data[i].equalsIgnoreCase(strRain)) {
                return i;
            }
        }
        return -1;
    }

    private List<String> m_inputForecastList = new ArrayList<String>();
    private List<String> m_inputRealityList = new ArrayList<String>();
    private List<String> m_listCSV = new ArrayList<String>();

    private String m_strStationId;
    private String m_strLon;
    private String m_strLat;
    private String m_strDate;
    private String m_strTemp;
    private String m_strMaxTemp;
    private String m_strRain;
    private String m_strHumidity;

    private String m_strBeginDate;
}
